import { launchPay } from "../../api/pay/payApi";
import { getRandomMoney } from "../../utils/tools";
import { AlipaySubmit } from "./AlipaySubmit";
import querystring from "querystring";
import { MONEY } from "./PayConfig";

const alipayConfig = {
  apiurl: "https://m1.duai1.cn/",
  key: "fSY3ZWEolQw",
  sign_type: "MD5",
  input_charset: "UTF-8",
};

const alipaySubmit = new AlipaySubmit(alipayConfig);

function createParams(money: string, returnUrl: string): any {
  const paraTemp = {
    pid: "196309431", // 商户ID
    type: "wxpay", // 支付方式
    out_trade_no: Date.now() + Math.random().toString().slice(2, 5), // 商户订单号
    notify_url: "/321312", // 异步通知地址
    return_url: returnUrl + "/code.html", // 页面跳转通知地址
    name: "付款后需要留在当前页面，会有2~5s的延迟，不要急着关闭页面", // 商品名称
    money, // 商品金额
    sitename: "傲慢", // 网站名称
  };

  return alipaySubmit.buildRequestPara(paraTemp);
}

export class PayService {
  public static async pay(returnUrl: string): Promise<any> {
    const money = getRandomMoney(MONEY);
    const url = `https://m1.duai1.cn/submit.php?${querystring.stringify(createParams(String(money), returnUrl))}`;

    const resp: any = await launchPay(url);

    const regex = /window\.location\.href='([^']+)'/;
    const match = resp.match(regex);

    if (match && match[1]) {
      return `https://m1.duai1.cn/${match[1]}`;
    }
    return resp;
  }
}
